#include "processdatamanager.h"

ProcessDataManager::ProcessDataManager(QObject *parent) : QObject(parent)
{
    initDatabase();
    initTable();
}


void ProcessDataManager::initDatabase()
{
    // 检查数据库驱动
    if (!QSqlDatabase::isDriverAvailable("QSQLITE")) {
        qCritical() << "数据库驱动QSQLITE不可用！";
        return;
    }

    // 配置数据库（确保路径正确，有写入权限）
    QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE");
    db.setDatabaseName("./process_data.db"); // 检查此路径是否正确

    // 验证数据库是否能打开（关键）
    if (!db.open()) {
        qCritical() << "数据库打开失败：" << db.lastError().text();
        qCritical() << "目标文件路径：" << db.databaseName();
        qCritical() << "文件是否存在：" << QFile::exists(db.databaseName());
        qCritical() << "文件是否可写：" << QFile::permissions(db.databaseName()) /*& QFile::WriteUser*/;
        return;
    }

    qDebug() << "数据库连接成功，文件路径：" << db.databaseName();
}

bool ProcessDataManager::initTable()
{
    // 先尝试查询表，验证是否存在
    QString checkSql = "SELECT id, Name FROM ProcessParameter;";
    qDebug() << "Cpp: 检查数据表 ProcessParameter 是否存在，执行SQL:" << checkSql;

    bool checkOk = m_db->execSql(checkSql);
    if (!checkOk)
    {
        // 查询失败，认为表不存在，执行创建操作
        qDebug() << "Cpp: 不存在数据表 ProcessParameter，准备创建";

        QString createSql = "CREATE TABLE ProcessParameter ("
                            "id INTEGER PRIMARY KEY AUTOINCREMENT, "
                            "Name TEXT, "
                            "Process1 TEXT, "
                            "Process2 TEXT, "
                            "F_UpperKnife01Assist TEXT, "
                            "F_UpperKnife02Assist TEXT, "
                            "B_UpperKnife01Assist TEXT, "
                            "B_UpperKnife02Assist TEXT, "
                            "F_UpperKnife01 TEXT, "
                            "F_UpperKnife02 TEXT, "
                            "B_UpperKnife01 TEXT, "
                            "B_UpperKnife02 TEXT, "
                            "F_LowerKnife01 TEXT, "
                            "F_LowerKnife02 TEXT, "
                            "B_LowerKnife01 TEXT, "
                            "B_LowerKnife02 TEXT, "
                            "Roller TEXT);";

        qDebug() << "Cpp: 创建数据表 ProcessParameter，执行SQL:" << createSql;
        bool createOk = m_db->execSql(createSql);
        if (createOk)
        {
            qDebug() << "Cpp: 创建数据表 ProcessParameter 成功";
            return true;
        }
        else
        {
            qDebug() << "Cpp: 创建数据表 ProcessParameter 失败";
            return false;
        }
    }
    else
    {
        // 表已存在，无需操作（可根据需要添加初始化逻辑）
        qDebug() << "Cpp: 数据表 ProcessParameter 已存在";
        return true;
    }

}

void ProcessDataManager::getAllData()
{
    m_model->clear();
    QString sql = "SELECT id, Name, Process1, Process2, "
                  "F_UpperKnife01Assist, F_UpperKnife02Assist, B_UpperKnife01Assist, B_UpperKnife02Assist, "
                  "F_UpperKnife01, F_UpperKnife02, B_UpperKnife01, B_UpperKnife02, "
                  "F_LowerKnife01, F_LowerKnife02, B_LowerKnife01, B_LowerKnife02, Roller "
                  "FROM ProcessParameter ORDER BY id ASC;";

    QSqlQuery *query = m_db->execSqlResult(sql);
    if (!query) return;

    while (query->next()) {
        ParameterItem *item = new ParameterItem();
        item->setId(query->value(0).toInt());
        item->setName(query->value(1).toString());
        item->setProcess1(query->value(2).toString());
        item->setProcess2(query->value(3).toString());
        item->setF_UpperKnife01Assist(query->value(4).toString());
        item->setF_UpperKnife02Assist(query->value(5).toString());
        item->setB_UpperKnife01Assist(query->value(6).toString());
        item->setB_UpperKnife02Assist(query->value(7).toString());
        item->setF_UpperKnife01(query->value(8).toString());
        item->setF_UpperKnife02(query->value(9).toString());
        item->setB_UpperKnife01(query->value(10).toString());
        item->setB_UpperKnife02(query->value(11).toString());
        item->setF_LowerKnife01(query->value(12).toString());
        item->setF_LowerKnife02(query->value(13).toString());
        item->setB_LowerKnife01(query->value(14).toString());
        item->setB_LowerKnife02(query->value(15).toString());
        item->setRoller(query->value(16).toString());

        m_model->addItem(item);
    }


    emit dataLoaded(m_model);
    delete query;
}

void ProcessDataManager::addData()
{
    QString sql = "INSERT INTO ProcessParameter ("
                  "Name, Process1, Process2, "
                  "F_UpperKnife01Assist, F_UpperKnife02Assist, B_UpperKnife01Assist, B_UpperKnife02Assist, "
                  "F_UpperKnife01, F_UpperKnife02, B_UpperKnife01, B_UpperKnife02, "
                  "F_LowerKnife01, F_LowerKnife02, B_LowerKnife01, B_LowerKnife02, Roller"
                  ") VALUES ('新参数', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '');";

    if (m_db->execSql(sql)) {
        getAllData();
    }
}

void ProcessDataManager::deleteData(int id)
{
    QString sql = QString("DELETE FROM ProcessParameter WHERE id = %1;").arg(id);
    if (m_db->execSql(sql)) {
        getAllData();
    }
}

void ProcessDataManager::saveData(int id, const QString &propertyName, const QString &value)
{
    // 1. 检查数据库连接状态
    QSqlDatabase db = QSqlDatabase::database();
    if (!db.isOpen()) {
        qCritical() << "保存失败：数据库未连接";
        return;
    }

    // 2. 构造SQL语句（关键：确保表名和列名与数据库结构完全一致）
    // 表名假设为"process_parameters"，根据实际表名修改
    // 列名必须与QML中传递的propertyName完全一致（区分大小写）
    QString sql = QString("UPDATE ProcessParameter "
                          "SET %1 = :value "  // 使用参数绑定避免SQL注入
                          "WHERE id = :id");
    sql = sql.arg(propertyName); // 替换列名

    QSqlQuery query(db);
    query.prepare(sql);
    query.bindValue(":value", value);
    query.bindValue(":id", id);

    // 3. 执行SQL并检查结果
    if (!query.exec()) {
        // 输出详细错误信息（关键排查依据）
        qCritical() << "保存失败！ID:" << id << "属性:" << propertyName;
        qCritical() << "SQL语句:" << query.lastQuery();
        qCritical() << "错误原因:" << query.lastError().text();
        return;
    }

    // 4. 对于SQLite，默认自动提交，如需手动提交：
    // db.commit();

    qDebug() << "保存成功 | ID:" << id << "属性:" << propertyName << "值:" << value;
}

void ProcessDataManager::searchData(const QString &keyword)
{
    // 清空现有模型数据
    m_model->clear();

    QSqlDatabase db = QSqlDatabase::database();
    if (!db.isOpen()) {
        qCritical() << "数据库未连接";
        emit dataLoaded(m_model); // 发送空模型
        return;
    }

    // 注意：表名与类中保持一致使用"ProcessParameter"（首字母大写）
    QString sql = QString("SELECT id, Name, Process1, Process2, "
                          "F_UpperKnife01Assist, F_UpperKnife02Assist, "
                          "B_UpperKnife01Assist, B_UpperKnife02Assist, "
                          "F_UpperKnife01, F_UpperKnife02, "
                          "B_UpperKnife01, B_UpperKnife02, "
                          "F_LowerKnife01, F_LowerKnife02, "
                          "B_LowerKnife01, B_LowerKnife02, Roller "
                          "FROM ProcessParameter WHERE "
                          "Name LIKE :keyword OR "
                          "Process1 LIKE :keyword OR "
                          "Process2 LIKE :keyword OR "
                          "F_UpperKnife01Assist LIKE :keyword OR "
                          "F_UpperKnife02Assist LIKE :keyword OR "
                          "B_UpperKnife01Assist LIKE :keyword OR "
                          "B_UpperKnife02Assist LIKE :keyword OR "
                          "F_UpperKnife01 LIKE :keyword OR "
                          "F_UpperKnife02 LIKE :keyword OR "
                          "B_UpperKnife01 LIKE :keyword OR "
                          "B_UpperKnife02 LIKE :keyword OR "
                          "F_LowerKnife01 LIKE :keyword OR "
                          "F_LowerKnife02 LIKE :keyword OR "
                          "B_LowerKnife01 LIKE :keyword OR "
                          "B_LowerKnife02 LIKE :keyword OR "
                          "Roller LIKE :keyword "
                          "ORDER BY id ASC;");

    QSqlQuery query(db);
    query.prepare(sql);
    // 绑定模糊搜索参数，添加通配符
    query.bindValue(":keyword", "%" + keyword + "%");

    if (!query.exec()) {
        qCritical() << "搜索失败：" << query.lastError().text();
        qCritical() << "执行的SQL：" << query.lastQuery();
        emit dataLoaded(m_model); // 发送空模型
        return;
    }

    // 解析查询结果到模型
    while (query.next()) {
        ParameterItem *item = new ParameterItem();
        item->setId(query.value(0).toInt());
        item->setName(query.value(1).toString());
        item->setProcess1(query.value(2).toString());
        item->setProcess2(query.value(3).toString());
        item->setF_UpperKnife01Assist(query.value(4).toString());
        item->setF_UpperKnife02Assist(query.value(5).toString());
        item->setB_UpperKnife01Assist(query.value(6).toString());
        item->setB_UpperKnife02Assist(query.value(7).toString());
        item->setF_UpperKnife01(query.value(8).toString());
        item->setF_UpperKnife02(query.value(9).toString());
        item->setB_UpperKnife01(query.value(10).toString());
        item->setB_UpperKnife02(query.value(11).toString());
        item->setF_LowerKnife01(query.value(12).toString());
        item->setF_LowerKnife02(query.value(13).toString());
        item->setB_LowerKnife01(query.value(14).toString());
        item->setB_LowerKnife02(query.value(15).toString());
        item->setRoller(query.value(16).toString());

        m_model->addItem(item);
    }

    // 发送包含搜索结果的模型到QML
    emit dataLoaded(m_model);
}

